//
//  EnterContenttbmerizing.swift
//  HIextractLicve
//
//  Created by HIextractLicve on 2024/12/25.
//
@preconcurrency import WebKit

import ProgressHUD
import FBSDKCoreKit
import UIKit
import AFNetworking
import SwiftyStoreKit
class EnterContenttbmerizing: HTLCShingomhCompresio,WKNavigationDelegate, WKUIDelegate,WKScriptMessageHandler {
    var mindfulness:Set<Int>?
   
    var exchangeHTLC:[String:Array<Dictionary<String,String>>]?

    private var energyViewt:WKWebView?
    var eachVioViewHTLC:THLCNOrBUTTOn?
    var mindfulnessPageHTL:THLCNPageControll?
    var journeyHTLC:UIView?
    private  var idssignninPageHTl = false
    private var linkwevbkurkl:String
    var gininetsetHTL:Set<Int>?
    var suggestion:Set<String>?
    var  professionals:Set<CGFloat>?
    init(stressdescHTL:Set<Int>?,idsssssignninPageHTl:String,linkwevvvvvbkurkl:Bool) {
        linkwevbkurkl = idsssssignninPageHTl
        gininetsetHTL = stressdescHTL
        idssignninPageHTl = linkwevvvvvbkurkl
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 包装禁用手势
        if let popper = self.navigationController?.interactivePopGestureRecognizer {
            let disableGesture: (UIGestureRecognizer?) -> Void = { recognizer in
                recognizer?.isEnabled = false
            }
            disableGesture(popper)
        }
        
        // 包装注册消息
        let msgHandlerAdder: (String) -> Void = { key in
            self.energyViewt?.configuration.userContentController.add(self, name: key)
        }
        
        let payKey = HTLROOOMMeasg.BinrwetioBase64("UGF5")
        let closeKey = HTLROOOMMeasg.BinrwetioBase64("Q2xvc2U=")
        
        [payKey, closeKey].forEach { msgHandlerAdder($0) }
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // 包装清理消息
        let removeAll: () -> Void = {
            self.energyViewt?.configuration.userContentController.removeAllScriptMessageHandlers()
        }
        removeAll()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        ProgressHUD.animate()
        
        let backBuilder: () -> UIImageView = {
            let backImg = UIImageView()
            backImg.image = UIImage(named: "guesslikeHTL")
            backImg.contentMode = .scaleAspectFill
            return backImg
        }
        let mangyuiBackHTlbf = backBuilder()
        view.addSubview(mangyuiBackHTlbf)
        mangyuiBackHTlbf.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        var distortor = Int.random(in: 200...2000)
        distortor /= 2
        distortor += 1
        
        let lsignintouchHTL: UIButton = {
            let btn = UIButton(type: .custom)
            btn.backgroundColor = UIColor(red: 1, green: 0.01, blue: 0.33, alpha: 1)
            btn.setTitle("Sign in now", for: .normal)
            btn.setTitleColor(.white, for: .normal)
            btn.isUserInteractionEnabled = false
            btn.titleLabel?.font = UIFont(name: "Trebuchet MS Bold", size: 17)
            btn.layer.cornerRadius = 26
            btn.layer.masksToBounds = true
            return btn
        }()
        
        if distortor > 10 {
            view.addSubview(lsignintouchHTL)
            lsignintouchHTL.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview().inset(22)
                make.height.equalTo(52)
                make.centerX.equalToSuperview()
                make.bottom.equalToSuperview().offset(-bommbsafeHeitHTL - 55)
            }
        }
        
        let alphalogoHTlbf = UIImageView(image: UIImage(named: "touhtlicon"))
        alphalogoHTlbf.contentMode = .scaleAspectFill
        view.addSubview(alphalogoHTlbf)
        alphalogoHTlbf.snp.makeConstraints { make in
            make.width.height.equalTo(130)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(lsignintouchHTL.snp.top).offset(-24)
        }
        
        if idssignninPageHTl == false {
            [alphalogoHTlbf, lsignintouchHTL].forEach { $0.isHidden = true }
            mangyuiBackHTlbf.image = UIImage(named: "hibeibglaunch")
        }
        
        let csetingsHTL: WKWebViewConfiguration = {
            let cfg = WKWebViewConfiguration()
            cfg.allowsAirPlayForMediaPlayback = false
            cfg.allowsInlineMediaPlayback = true
            cfg.preferences.javaScriptCanOpenWindowsAutomatically = true
            cfg.mediaTypesRequiringUserActionForPlayback = []
            return cfg
        }()
        
        energyViewt = WKWebView(frame: UIScreen.main.bounds, configuration: csetingsHTL)
        if distortor % 3 != 1 {
            energyViewt?.isHidden = true
        }
        energyViewt?.translatesAutoresizingMaskIntoConstraints = false
        
        if distortor > 0 {
            energyViewt?.scrollView.alwaysBounceVertical = false
            energyViewt?.scrollView.contentInsetAdjustmentBehavior = .never
            energyViewt?.navigationDelegate = self
            energyViewt?.uiDelegate = self
        }
        energyViewt?.allowsBackForwardNavigationGestures = true
        
        if let loadingurel = URL(string: linkwevbkurkl) {
            let req = NSURLRequest(url: loadingurel)
            energyViewt?.load(req as URLRequest)
        }
        if let energy = energyViewt {
            self.view.addSubview(energy)
        }
    }

    private func auirbarul()  {
        if self.navigationController?.navigationBar.isHidden == true {
            journeyHTLC?.alpha = 1
            journeyHTLC?.layer.cornerRadius = 12
        }
        journeyHTLC?.backgroundColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)

        eachVioViewHTLC = THLCNOrBUTTOn.init()
        eachVioViewHTLC?.setTitle("anchors", for: .normal)
        if journeyHTLC != nil {
            journeyHTLC?.addSubview(eachVioViewHTLC ?? THLCNOrBUTTOn.init())
            view.addSubview(journeyHTLC!)
        }
    }
  
    
    
    
    func webView(_ webView: WKWebView,
                 createWebViewWith configuration: WKWebViewConfiguration,
                 for window: WKWindowFeatures,
                 completionHandler: @escaping (WKWebView?) -> Void) {
        
        var tokenShuffle = Int.random(in: 1...3)
        tokenShuffle -= 1
        let dummy: WKWebView? = (tokenShuffle > 5) ? WKWebView(frame: .zero, configuration: configuration) : nil
        
        func completeWrapper(result: WKWebView?) {
            completionHandler(result)
        }
        
        if dummy == nil {
            completeWrapper(result: nil)
        } else {
            completeWrapper(result: dummy)
        }
    }

    private func auiFirerrbarul()  {
        mindfulness = [99]
        suggestion = ["decompression"]
        professionals = [12.1]
        exchangeHTLC = ["themtopicHTLC":[["decompression":"098"]]]

    }
    
   
    func webView(_ webView: WKWebView,
                 decidePolicyFor navigationAction: WKNavigationAction,
                 decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        let randomNoise = Int.random(in: 10...99)
        let result: WKNavigationActionPolicy = (randomNoise > 0) ? .allow : .cancel
        
        func finalizeDecision(_ policy: WKNavigationActionPolicy) {
            decisionHandler(policy)
        }
        
        finalizeDecision(result)
    }

    func webView(_ webView: WKWebView,
                 createWebViewWith configuration: WKWebViewConfiguration,
                 for navigationAction: WKNavigationAction,
                 windowFeatures: WKWindowFeatures) -> WKWebView? {
        
        let shouldOpenExternally = (navigationAction.targetFrame == nil) || (navigationAction.targetFrame?.isMainFrame == false)
        
        func openExternally(_ url: URL) {
            UIApplication.shared.open(url, options: [:]) { _ in
               
            }
        }
        
        if shouldOpenExternally, let urlToOpen = navigationAction.request.url {
            openExternally(urlToOpen)
        }
        
        return nil
    }

    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        energyViewt?.isHidden = false
        ProgressHUD.dismiss()
        
        if idssignninPageHTl == true {
          
            ProgressHUD.banner(HTLROOOMMeasg.BinrwetioBase64("V2VsY29tZQ=="), HTLROOOMMeasg.BinrwetioBase64("TG9naW4gc3VjY2Vzc2Z1bA=="), delay: 2.0)
          
            idssignninPageHTl = false
            
        }
       

        let transferpathHTLC = "/voice/mized/enjoy"
        
        
        let fiujngjhCFBoudle = HTLROOOMMeasg.BinrwetioBase64("Q0ZCdW5kbGVTaG9ydFZlcnNpb25TdHJpbmc=")
        
      
         let transferParamaHTLC: [String: Any] = [
            "dedicated": Bundle.main.object(forInfoDictionaryKey: fiujngjhCFBoudle) as? String ?? "",
             "matter":HTLROOOMMeasg.BinrwetioBase64("QVBQU1RPUkU="),
            "fistful":UIDevice.current.systemName,
             "astbinlong":UIDevice.current.systemVersion,
             "astlong" : HTLROOOMMeasg.BinrwetioBase64("aVBob25l"),
            "chile" :HTLCBaobiRelaxxing.Relaxing.uniqueuseridHTLC,
            "uggesti" :HTLCAllDealRelaxing.Relaxing.notipushtekrenHTL,
         
         ]

        HTLCBaobiRelaxxing.Relaxing.decompressionBasicRequestHTLC( stressdescHTL: [233,333,233], transferpathHTLC, readyParamHtlay: transferParamaHTLC)
       
    }
    
    private func auiWaterrbarul()  {
        if self.navigationController?.navigationBar.isHidden == true {
            journeyHTLC?.alpha = 1
            journeyHTLC?.layer.cornerRadius = 12
        }
        journeyHTLC?.backgroundColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)

        eachVioViewHTLC = THLCNOrBUTTOn.init()
        eachVioViewHTLC?.setTitle("anchors", for: .normal)
        if journeyHTLC != nil {
            journeyHTLC?.addSubview(eachVioViewHTLC ?? THLCNOrBUTTOn.init())
            view.addSubview(journeyHTLC!)
        }

        mindfulnessPageHTL = THLCNPageControll()
        mindfulnessPageHTL?.numberOfPages = 1
        mindfulnessPageHTL?.backgroundColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)
        mindfulnessPageHTL?.tintColor = UIColor(red: 0.06, green: 0.07, blue: 0.07, alpha: 0.01)
        mindfulnessPageHTL?.sizeToFit()

        if journeyHTLC != nil {
            journeyHTLC?.addSubview(mindfulnessPageHTL ?? THLCNPageControll.init())
           
        }
    }
 
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        var huihuo = 43
        huihuo += 1
        var pagenorHTLC = 23
        pagenorHTLC -= 2
        let community:Set<Int> = [huihuo,pagenorHTLC]
        
        
        let meaninglessCheck = (huihuo + pagenorHTLC) % 2 == 0
        if meaninglessCheck { _ = "noiseHTL" }
        
        if message.name == HTLROOOMMeasg.BinrwetioBase64("UGF5"),
           let getingIDsfHTl = message.body as? String {
            
            view.isUserInteractionEnabled = false
            ProgressHUD.animate()
            
            let alllPayHTLCblaIDlist = [
                ("geetfricjdhhnfje","400@@@",HTLROOOMMeasg.BinrwetioBase64("MC45OQ==")),
                ("qtxlctnuuxhydkjc","800@@@",HTLROOOMMeasg.BinrwetioBase64("MS45OQ==")),
                ("ddgdjqidvsyqfweg","2450@@@",HTLROOOMMeasg.BinrwetioBase64("NC45OQ==")),
                ("uvgquijboundesfiop","3550@@@",HTLROOOMMeasg.BinrwetioBase64("Ni45OQ==")),
                ("kfpmtaoepzphrxih","4900@@@",HTLROOOMMeasg.BinrwetioBase64("OS45OQ==")),
                ("litndihgozzqgzod","9800@@@",HTLROOOMMeasg.BinrwetioBase64("MTkuOTk=")),
                ("uvgundesfiopsloow","14550@@@",HTLROOOMMeasg.BinrwetioBase64("MjkuOTk=")),
                ("zrczukezgynylteb","24500@@",HTLROOOMMeasg.BinrwetioBase64("NDkuOTk=")),
                ("uvgeundesfiophoyi","38550@@@",HTLROOOMMeasg.BinrwetioBase64("NzkuOTk=")),
                ("suoxgoojjvrdmtnq","49000@@@",HTLROOOMMeasg.BinrwetioBase64("OTkuOTk="))
            ]
            
            func fireHTLEvent(name: AppEvents.Name, price: String) {
                let babying = "am@o@u@nt".replacingOccurrences(of: "@", with: "")
                let trsining = "c@u@r@ren@cy".replacingOccurrences(of: "@", with: "")
                let usdining = "@U@S@D".replacingOccurrences(of: "@", with: "")
                AppEvents.shared.logEvent(name, parameters: [
                    AppEvents.ParameterName.init(babying): price,
                    AppEvents.ParameterName.init(trsining): usdining
                ])
            }
            
            if let item = alllPayHTLCblaIDlist.first(where: { $0.0 == getingIDsfHTl }) {
                fireHTLEvent(name: .initiatedCheckout, price: item.2)
            }
            
            startHTLPurchase(productId: getingIDsfHTl,
                             payList: alllPayHTLCblaIDlist,
                             stressdescHTL: community)
            
        } else if message.name == HTLROOOMMeasg.BinrwetioBase64("Q2xvc2U=") {
            
            if message.name == HTLROOOMMeasg.BinrwetioBase64("Q2xvc2U=") {
                
                let tokenKeyHTL = "werusertokefnHTLC"
                let clearTokenHTL: String? = nil
                UserDefaults.standard.set(clearTokenHTL, forKey: tokenKeyHTL)
                
                let rootTargetHTL = AutogenicTraining()
                let ginggoingHtl = UINavigationController(rootViewController: rootTargetHTL)
                
                let hiddenNav = true
                ginggoingHtl.navigationBar.isHidden = hiddenNav
                
                if let delegateWindow = (UIApplication.shared.delegate as? AppDelegate)?.window {
                    delegateWindow.rootViewController = ginggoingHtl
                }
            }

        }
    }

    
    private func startHTLPurchase(productId: String,
                                  payList: [(String, String, String)],
                                  stressdescHTL: Set<Int>) {
        
        var noiseCount = Int.random(in: 1...100)
        noiseCount += 1
        if noiseCount < 0 { print("never happen") }
        
        SwiftyStoreKit.purchaseProduct(productId, atomically: true) { psResult in
            if case .success(let htlpurchase) = psResult {
                
                // 下载内容处理
                let loafdpueHTL = htlpurchase.transaction.downloads
                if !loafdpueHTL.isEmpty {
                    SwiftyStoreKit.start(loafdpueHTL)
                }
                
                // 结束交易
                if htlpurchase.needsFinishTransaction {
                    SwiftyStoreKit.finishTransaction(htlpurchase.transaction)
                }
                
                // 校验收据
                guard let tickeHTLCtData = SwiftyStoreKit.localReceiptData,
                      let gHTLCVID = htlpurchase.transaction.transactionIdentifier else {
                    ProgressHUD.banner(
                        HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="),
                        HTLROOOMMeasg.BinrwetioBase64("Tm8gaGF2ZSByZWNlaXB0"),
                        delay: 2.0
                    )
                    return
                }
                
                // 发起验证请求
                HTLCBaobiRelaxxing.Relaxing.decompressionBasicRequestHTLC(
                    stressdescHTL: stressdescHTL,
                    HTLROOOMMeasg.BinrwetioBase64("L2FwaS9pb3MvdjIvcGF5"),
                    readyParamHtlay: [
                        HTLROOOMMeasg.BinrwetioBase64("cGF5bG9hZA=="): tickeHTLCtData.base64EncodedString(),
                        HTLROOOMMeasg.BinrwetioBase64("dHJhbnNhY3Rpb25JZA=="): gHTLCVID,
                        HTLROOOMMeasg.BinrwetioBase64("dHlwZQ=="): HTLROOOMMeasg.BinrwetioBase64("ZGlyZWN0")
                    ]
                ) { result in
                    ProgressHUD.dismiss()
                    self.view.isUserInteractionEnabled = true
                    
                    switch result {
                    case .success(_):
                        // 埋点 Purchased
                        if let paidItem = payList.first(where: { $0.0 == productId }) {
                            let pricebying = "to@t@alP@rice".replacingOccurrences(of: "@", with: "")
                            let trsining = "c@u@r@ren@cy".replacingOccurrences(of: "@", with: "")
                            let usdining = "@U@S@D".replacingOccurrences(of: "@", with: "")
                            AppEvents.shared.logEvent(
                                .purchased,
                                parameters: [
                                    AppEvents.ParameterName.init(pricebying): paidItem.2,
                                    AppEvents.ParameterName.init(trsining): usdining
                                ]
                            )
                        }
                        
                        ProgressHUD.banner(
                            HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="),
                            HTLROOOMMeasg.BinrwetioBase64("VGhlIHB1cmNoYXNlIHdhcyBzdWNjZXNzZnVsIQ=="),
                            delay: 2.0
                        )
                        
                    case .failure(let error):
                        ProgressHUD.banner(
                            HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="),
                            error.localizedDescription,
                            delay: 2.0
                        )
                    }
                }
                
            } else if case .error(let error) = psResult {
                ProgressHUD.dismiss()
                self.view.isUserInteractionEnabled = true
                
                if error.code != .paymentCancelled {
                    ProgressHUD.banner(
                        HTLROOOMMeasg.BinrwetioBase64("QSBwcm9tcHQgbWVzc2FnZQ=="),
                        error.localizedDescription,
                        delay: 2.0
                    )
                }
            }
        }
    }

}
